package com.iss.card.webservice;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.iss.card.view.model.ResponseBean;

import android.util.Log;

/**
 * sax parse xml
 */
public class XMLContentHandler extends DefaultHandler {
	private static final String TAG = XMLContentHandler.class.getSimpleName();
	private ResponseBean mResponseData;
	private List<BaseModel> modeList;
	private Class<? extends BaseModel> childInfo;
	private BaseModel baseMode;
	private static final String STATUS_STRING = "status";
	private static final String MESSAGE_STRING = "message";
	private static final String DATA_STRING = "data";

	private String mTagValue;

	public XMLContentHandler() {
		super();
	}

	public XMLContentHandler(Class<? extends BaseModel> childInfo) {
		mResponseData = new ResponseBean();
		modeList = new ArrayList<BaseModel>();
		mResponseData.arrayList = (ArrayList<BaseModel>) modeList;
		this.childInfo = childInfo;
	}

	public ResponseBean getModel() {
		return mResponseData;
	}

	/**  
	 *
	 */
	@Override
	public void startDocument() throws SAXException {
	}

	/**  
	 * 
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String value = new String(ch, start, length);
		mTagValue = mTagValue + value;
	}

	/**  
	 * 
	 */
	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		if (DATA_STRING.equals(localName)) {
			try {
				baseMode = childInfo.newInstance();
			} catch (InstantiationException e) {
				Log.e(TAG, "InstantiationException:");
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				Log.e(TAG, "IllegalAccessException:");
				e.printStackTrace();
			}
		}

		mTagValue = "";
	}

	/**  
	 * 
	 */
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if (STATUS_STRING.equals(localName)) {	// set status.
			if (mResponseData != null) {
				mResponseData.setStatus(mTagValue);
			}
		} else if (MESSAGE_STRING.equals(localName)) {	// set message.
			if (mResponseData != null) {
				mResponseData.setMessage(mTagValue);
			}
		} else if (DATA_STRING.equals(localName)) {	// set data.
			if (baseMode != null) {
				modeList.add(baseMode);
				baseMode = null;
			}
		} else {	// add each item's value.
			if (baseMode != null && !("\n").equals(localName)
					&& localName != null) {
				baseMode.addValues(localName, mTagValue, baseMode);
			}
		}
		
		// clear previous value.
		mTagValue = "";
	}
}